<template>
  <view class="my-login">
    <view class="login-container">
      <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
      <button class="btn-login" type="primary" open-type="getUserInfo" @click="getUserProfile">一键登录</button>
      <text class="tips-text">登录尽享更多权益</text>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'

  export default {
    name: "my-login",
    data() {
      return {

      };
    },
    computed: {
      ...mapState('m_user', ['redirectInfo']),
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
      async getUserProfile(e) {
        let that = this;
        const res = await uni.getUserProfile({
          desc: '用于获取您的个人信息',
          // success: res => console.log(res.userInfo),
          fail: res => uni.$showMsg('您取消了登录授权！'),
          complete: res => {
            that.updateUserInfo(res)
            that.getToken(res)

          },
        });
        // 以后都不会再这里储存用户的微信头像和名称了，要么直接用手机号登录，要么用户自己去设置头像和用户名
        /*  that.updateUserInfo(e.detail.userInfo);
          that.getToken(e.detail);
                     getUserInfo(e){
                       if(e.detail.errMsg === 'getUserInfo:fail auth deny')
                         return uni.$showMsg('您取消了登录授权！')
                         console.log(e.detail.userInfo)
                     }, */
      },
      //登录获取Token字符串,登录第二步（用uni.login()获取code，集齐5个参数调登录接口，获取token）

      async getToken(info) {
        // 获取 code 对应的值

        const res = await uni.login().catch(err => err);
        if (res.errMsg !== "login:ok") return uni.$showMsg('登录失败！');
        // 准备参数
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        };
        // console.log('这是info中的userInfo：');
        // console.log(info.userInfo);
        // console.log(query);
        // 调登录接口（登录接口失效才导致登录失败，这个登录过程是对的，只是接口失效，手动给vuex里面的token随便写个值就可以进行后面的开发了）
        const {
          data: loginResult
        } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        //在判断登录之前设置假token
        this.updateToken(
          'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
          )
        // console.log(loginResult)
        if (loginResult.meta.status == 200){
          return uni.$showMsg('登录失败22！')
        } 
        this.navigateBack();
        uni.$showMsg('登录成功！');
        // 直接把 token 保存到 vuex 中
        // this.updateToken(loginResult.message.token);
        /* const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin', query);
     			这个是正确的写法 if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！');
          表示登录成功，跳转到登录详情页
     			this.navigateBack(); */
      },
      navigateBack(){
        if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
          uni.switchTab({
            url: this.redirectInfo.from,
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      },
    }
  }
</script>

<style lang="scss">
  page,
  .my-login {
    height: 100%;
    background-color: white;
  }

  .login-container {
    height: 750rpx;
    background-color: #f8f8f8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;

    &::after {
      content: '';
      background-color: white;
      display: block;
      width: 100%;
      height: 40px;
      bottom: 0;
      left: 0;
      border-radius: 100%;
      transform: translateY(224%);
    }

    .btn-login {
      background-color: #c00000;
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
    }

    .tips-text {
      color: gray;
      font-size: 12px;
    }
  }
</style>